<template>
  <div>
    <Row style="align-items: flex-start;margin-bottom:5px;display:block">
      <Col :lg="10" :xs="22" offset="0.5">
      <vxe-toolbar :refresh="{ query: reload }" print v-if="isUpdate">
        <template #buttons>
          <vxe-button size="mini" status="primary" @click="impotEvent">导入</vxe-button>
          <vxe-button size="mini" status="primary" @click="exportFile">导出</vxe-button>
          <vxe-button size="mini" status="primary" @click="addRow">新增</vxe-button>
          <vxe-button size="mini" status="danger" @click="delRow">删除</vxe-button>
          <vxe-button size="mini" @click="saveData">保存</vxe-button>
        </template>
      </vxe-toolbar>
      <vxe-table ref="xTable" height="400px" border highlight-hover-row show-overflow :edit-rules="validRules"
        class="sortable-row-demo" :data="tablePage.listPage" :print-config="{}" :export-config="{
          filename: filename(),
          columnFilterMethod: filterExport1,
          type: 'cvs'
        }" :loading="loading" :edit-config="{ trigger: 'click', mode: 'cell', enabled: isUpdate }">
        <vxe-column v-if="isUpdate" type="checkbox" width="60"></vxe-column>
        <vxe-column v-if="isUpdate" width="60">
          <template #default>
            <span class="drag-btn">
              <i class="vxe-icon--menu"></i>
            </span>
          </template>
          <template #header>
            <vxe-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
              <i class="vxe-icon--question" @click="showHelpTip1 = !showHelpTip1"></i>
            </vxe-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="speed" title="转速rpm" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="torque" title="扭矩Nm" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="bsfc" title="BSFC油耗率" :edit-render="{ name: 'input' }"></vxe-column>
        <vxe-column field="throat" title="油门" :edit-render="{ name: 'input' }"></vxe-column>
      </vxe-table>

      <vxe-pager :current-page="tablePage.currentPage" :page-size="tablePage.pageSize" :total="tablePage.totalResult"
        :layouts="[
          'PrevPage',
          'JumpNumber',
          'NextPage',
          'FullJump',
          'Sizes',
          'Total'
        ]" @page-change="handlePageChange">
      </vxe-pager>
      </Col>
      <Col :lg="12" :xs="22" offset="0.5">
      <div style="height:400px;" id="c"></div>
      <div style="height:400px;" id="d"></div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { torqueConverterLambdaApi } from "@/api/torque-converter-lambda";
import Sortable from "sortablejs";
import { engineApi } from "@/api/engine";
import { engineExternalCharacteristicApi } from "@/api/engine-external-characteristic";
import { engineReverseApi } from "@/api/engine-reverse";
import { engineThousandApi } from "@/api/engine-thousand";
import XEUtils from "xe-utils";
import XLSX, { WorkSheet } from "xlsx";
const PAGE_SIZE_INIT = 20;
export default {
  name: "EngCmp2",
  components: {},
  props: {
    id: {
      type: Number
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      validRules: {
        throat: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }],
        bsfc: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }],
        torque: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }],
        speed: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }]
      },
      sortable1: null,
      showHelpTip1: false,
      detail: {}, // 详情信息
      torqueConvertId: null,
      tableData: [], // 表格列表数据-- 总数据
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      }
    };
  },
  computed: {},
  watch: {
    /// 深度监听，可监听到对象、数组的变化  (table数据变化时，渲染echart)
    tableData: {
      handler(newVal, oldVal) {
        this.renderEchart();
      },
      deep: true // true 深度监听
    }
  },
  filters: {},
  created() {
    // 启动列名拖动
    this.columnDrop2();
  },
  mounted() {
    // 初始化数据
    this.initData();

    this.rowDrop();
  },
  methods: {
    filename() {
      var date = new Date();
       var dateStr = new Date(+new Date() + 8 * 3600 * 1000)
        .toJSON()
        .substr(0, 19)
        .replace("T", "")
        .replaceAll("-", "")
        .replaceAll(":", "")
      return ("万有特性曲线" + dateStr);
    },
    filterExport1(data) {
      // 返回false 就是导出不显示
      if (!data.column.title) return false;
      if (data.column.type == "checkbox") return false;
      return true;
    },
    exportFile() {
      this.$refs.xTable.exportData({ type: "csv" });
    },
    exportFile2() {
      this.$refs.xTable2.exportData({ type: "csv" });
    },
    // 刷新表格
    reload() {
      const $table = this.$refs.xTable;
      // 清除所有状态
      $table.clearAll();
      this.torqueConvertId = this.$route.query.id;
      // 初始化数据
      this.initData();
    },
    columnDrop2() {
      this.$nextTick(() => {
        const $table = this.$refs.xTable;
        this.sortable2 = Sortable.create(
          $table.$el.querySelector(
            ".body--wrapper>.vxe-table--header .vxe-header--row"
          ),
          {
            handle: ".vxe-header--column:not(.col--fixed)",
            onEnd: ({ item, newIndex, oldIndex }) => {
              const { fullColumn, tableColumn } = $table.getTableColumn();
              const targetThElem = item;
              const wrapperElem = targetThElem.parentNode;
              const newColumn = fullColumn[newIndex];
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(
                    targetThElem,
                    wrapperElem.children[oldIndex]
                  );
                } else {
                  wrapperElem.insertBefore(
                    wrapperElem.children[oldIndex],
                    targetThElem
                  );
                }
                return this.$XModal.message({
                  content: "固定列不允许拖动！",
                  status: "error"
                });
              }
              // 转换真实索引
              const oldColumnIndex = $table.getColumnIndex(
                tableColumn[oldIndex]
              );
              const newColumnIndex = $table.getColumnIndex(
                tableColumn[newIndex]
              );
              // 移动到目标列
              const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
              fullColumn.splice(newColumnIndex, 0, currRow);
              $table.loadColumn(fullColumn);
            }
          }
        );
      });
    },

    // 行数据移动
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable;
        this.sortable1 = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0];
              this.tableData.splice(newIndex, 0, currRow);
            }
          }
        );
      });
    },
    // 翻页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.findList();
    },

    findList() {
      // 总数据
      this.tablePage.totalResult = this.tableData.length;
      this.tablePage.listPage = this.tableData.slice(
        (this.tablePage.currentPage - 1) * this.tablePage.pageSize,
        this.tablePage.currentPage * this.tablePage.pageSize
      );
    },

    // 导入
    impotEvent() {
      this.$refs.xTable
        .readFile({
          types: ["xls", "xlsx", "csv"]
        })
        .then(params => {
          debugger;
          const { files } = params;
          const fileReader = new FileReader();
          fileReader.onload = ev => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1);
            const tableData = [];
            // 解析数据csvData
            csvData.split("\n").forEach((vRow, index) => {
              if (index == 0) {
                return;
              }
              if (vRow) {
                const vCols = vRow.split(",");
                const item = {};
                vCols.forEach((val, cIndex) => {
                  if (cIndex == 0) {
                    item["speed"] = val;
                  } else if (cIndex == 1) {
                    item["torque"] = val;
                  } else if (cIndex == 2) {
                    item["bsfc"] = val;
                  } else if (cIndex == 3) {
                    item["throat"] = val;
                  }
                  item["index"] = Number(
                    Math.random()
                      .toString()
                      .substr(2, 10) + Date.now()
                  ).toString(36);
                });
                tableData.push(item);
              }
            });
            this.tableData = tableData;
            this.findList();
          };
          fileReader.readAsBinaryString(files[0]);
        });
    },
    /**
     * @desc 渲染echart
     * @sicne 2021/11/13
     */
    renderEchart() {
      // 获取不重复的油门信息
      const throats = [];
      this.tableData.forEach(item => {
        if (item.throat && throats.indexOf(item.throat) == -1) {
          throats.push(item.throat);
        }
      });

      // 按照油门升序
      throats.sort(function (a, b) {
        return a - b;
      });

      // 转速-扭矩-油门曲线
      const series = [];

      // 转速-BSFC-油门曲线
      const series1 = [];

      // 生成[x, y]坐标轴
      throats.forEach(throat => {
        // 转速，扭矩
        const temp1 = [];
        let tempTableData = [...this.tableData];
        tempTableData.sort((a, b) => a.speed - b.speed); // 排序
        tempTableData
          .filter(item => {
            return item.throat == throat;
          })
          .forEach(item => {
            const temp = [];
            temp.push(item.speed);
            temp.push(item.torque);
            temp1.push(temp);
          });

        // 转速，BSFC
        const temp2 = [];
        let tempTableData2 = [...this.tableData];
        tempTableData2.sort((a, b) => a.speed - b.speed); // 排序
        tempTableData2
          .filter(item => {
            return item.throat == throat;
          })
          .forEach(item => {
            const temp = [];
            temp.push(item.speed);
            temp.push(item.bsfc);
            temp2.push(temp);
          });

        // 转速，空载损失----曲线
        series.push({
          id: "a" + throat,
          name: throat,
          type: "line",
          smooth: true,
          symbolSize: 5,
          data: temp1
        });

        series1.push({
          id: "a" + throat,
          name: throat,
          type: "line",
          smooth: true,
          symbolSize: 5,
          data: temp2
        });
      });

      const option = {
        title: {
          text: "转速-扭矩-油门曲线"
        },
        tooltip: {
          trigger: "item",
          formatter: function (item) {
            let str = "";
            str += `油门：${item.seriesName}<br/>转速：${item.data[0]}<br/>扭矩：${item.data[1]}`;
            str += "<br/>";
            return str;
          }
        },
        legend: {
          x: "right",
          data: throats,
          textStyle: {
            fontsize: 5
          }
        },
        grid: {
          left: "10%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },

        xAxis: {
          type: "value",
          name: "转速(rpm)",
          axisLine: { onZero: false },
          nameLocation: "center",
          splitLine: {
            show: false
          }
        },
        yAxis: [
          {
            name: "扭矩(Nm)",
            axisLine: {
              lineStyle: {
                color: "#102b6a"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            }
          }
        ],
        series: series
      };

      const option1 = {
        title: {
          text: "转速-BSFC-油门曲线"
        },
        tooltip: {
          trigger: "item",
          formatter: function (item) {
            let str = "";
            str += `油门：${item.seriesName}<br/>转速：${item.data[0]}<br/>BSFC：${item.data[1]}`;
            str += "<br/><br/>";
            return str;
          }
        },
        legend: {
          x: "right",
          data: throats,
          textStyle: {
            fontsize: 5
          }
        },
        grid: {
          left: "10%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: {
          type: "value",
          name: "转速(rpm)",
          axisLine: { onZero: false },
          nameLocation: "center",
          splitLine: {
            show: false
          }
        },
        yAxis: [
          {
            name: "BSFC",
            axisLine: {
              lineStyle: {
                color: "#102b6a"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            }
          }
        ],
        series: series1
      };

      const myChart = this.echarts.init(document.getElementById("c"));
      myChart.clear();
      myChart.setOption(option);

      const myChart1 = this.echarts.init(document.getElementById("d"));
      myChart1.clear();
      myChart1.setOption(option1);
    },

    /**
     * @desc 添加行数据
     */
    addRow() {
      const $table = this.$refs.xTable;
      const record = {
        speed: null,
        torque: null,
        throat: null,
        bsfc: null,
        massFlowRate: null,
        index: new Date().getTime()
      };
      this.tableData.push(record);
      this.findList();
      const { row: newRow } = $table.insertAt(record, -1);
      $table.setActiveCell(newRow, "speed");
      this.reRenderTable();
    },
    reRenderTable() {
      const newData = this.tablePage.listPage;
      this.tablePage.listPage = [];
      setTimeout(() => {
        this.tablePage.listPage = newData;
      }, 100);
    },

    /**
     * @desc 删除行数据
     */
    async delRow() {
      const { rows } = await this.$refs.xTable.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },

    saveData() {
      // 数据验证
      if (!(this.tableData && this.tableData.length > 0)) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }

      const speed = this.tableData.map(item => item.speed);
      const torque = this.tableData.map(item => item.torque);
      const throat = this.tableData.map(item => item.throat);
      const bsfc = this.tableData.map(item => item.bsfc);
      const massFlowRate = this.tableData.map(item => item.massFlowRate);

      const param = {
        speed: JSON.stringify(speed),
        torque: JSON.stringify(torque),
        throat: JSON.stringify(throat),
        bsfc: JSON.stringify(bsfc),
        massFlowRate: JSON.stringify(massFlowRate),
        tableData: JSON.stringify(this.tableData),
        engineId: this.id
      };
      this.loading = true;
      engineThousandApi
        .addEngineThousand(param)
        .then(res => {
          this.$Message.warning("保存成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 初始化列表数据
     */
    initData() {
      this.loading = true;
      engineThousandApi
        .getByEngineId(this.id)
        .then(res => {
          const data = res.data;
          if (data) {
            // 组合table数据

            const tableData = JSON.parse(data.tableData);
            if (tableData && tableData.length > 0) {
              this.tableData = tableData;
              this.findList();
              this.renderEchart();
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
<style>
.sortable-row-demo .drag-btn {
  cursor: move;
  font-size: 12px;
}

.sortable-row-demo .vxe-body--row.sortable-ghost,
.sortable-row-demo .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
</style>
<style>
#cont {
  background-color: #fff;
  padding-top: 10px;
}

.tb-row1 {
  border: 1px solid #eee;
}

.tb-row1>div {
  border-right: 1px solid #eee;
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  padding-left: 10px;
}

.tb-row1>div:first-child {
  color: #666;
  background: #f5f5f5;
  text-align: center;
  font-weight: bold;
}

.tb-row1>div:nth-child(3) {
  color: #666;
  background: #f5f5f5;
  text-align: left;
  font-weight: bold;
  text-align: center;
}

.tb-row1>div:last-child {
  border-right: 0;
}

.form-ex {
  margin-bottom: 20px;
}

.form-ex>div {
  width: 100px;
  display: inline;
}
</style>
